package org.finesys.quartz.config;


import lombok.RequiredArgsConstructor;
import org.finesys.common.quartz.core.constants.JobStatusEnum;
import org.finesys.quartz.entity.SysJob;
import org.finesys.quartz.service.SysJobService;
import org.finesys.quartz.support.JobScheduler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import java.util.List;

/**
 * 初始化加载定时任务
 */
@AutoConfiguration
@RequiredArgsConstructor
public class QuartzInitConfig implements InitializingBean {

    private final SysJobService sysJobService;

    private final JobScheduler jobScheduler;

    @Override
    public void afterPropertiesSet() throws Exception {
        //获取需要初始化的job任务
        List<SysJob> sysJobList = sysJobService.findAll();
        //遍历处理数据
        sysJobList.stream().forEach(sysJob -> {
            boolean exsitsJob = jobScheduler.exsitsJob(sysJob);

            //如果已发布状态，则删除定时任务
            if (JobStatusEnum.RELEASE.getValue().equals(sysJob.getJobStatus())) {
                if (exsitsJob) {
                    jobScheduler.delete(sysJob);
                }
            } else if (JobStatusEnum.RUNNING.getValue().equals(sysJob.getJobStatus())) {
                if (exsitsJob) {
                    //如果在运行状态，则恢复定时任务
                    jobScheduler.resume(sysJob);
                } else {
                    jobScheduler.add(sysJob);
                }
            } else if (JobStatusEnum.PAUSE.getValue().equals(sysJob.getJobStatus())) {
                //如果在暂停状态，则暂停定时任务
                if (exsitsJob) {
                    jobScheduler.pause(sysJob);
                } else {
                    jobScheduler.add(sysJob);
                    jobScheduler.pause(sysJob);
                }
            } else {
                //删除定时任务
                if (exsitsJob) {
                    jobScheduler.delete(sysJob);
                }
            }
        });
    }
}
